/**
 * Copyright (C) 2011 KingCore Science & Technology CO,.LTD. All rights reserved.
 * XNS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

/**
 * Copyright (C) 2002-2011 WUZEWEN. All rights reserved.
 * WUZEWEN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * This software is the confidential and proprietary information of
 * WuZeven, Personal. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with WuZeven.
 */

package com.kingcore.director.core.util;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.log4j.Logger;

import com.kingcore.director.DirectorConstants;

/**
 * <p>java类文件的说明...</p>
 * @author Zeven/wzw on May 19, 2011
 * @version	1.0
 * @see		Object#equals(java.lang.Object)
 * @since	JDK5
 */

public class DirectorStringUtils {
	
	//log object
	private final static Logger log = Logger.getLogger(DirectorStringUtils.class);

	
	public static String encodingUrl(String kw){
		return encodingUrl(kw, "utf-8");
	}
	
	public static String encodingUrl(String kw,String charset){
		try {
			kw = java.net.URLEncoder.encode( kw, charset); //," ","+"
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return kw ;
	}
	
	/**
	 * <p>下面的file:// 链接不能处理：   
	 *   <a href="file://D:\Program Files\KuGou\KuGou\KuGoo.exe">Open Music Now</a>
	 *   </p>
	 * @author Zeven on May 19, 2011
	 * @param content
	 * @return
	 */
	public static String addAnchorHtmlCode(String content){

		if (content==null || content.trim().length()<1) {
			return content;
		}
		content=content.replaceAll("([^(\")])(http|ftp|https|file)(://)(\\w+\\.\\w+([\\.\\w+]*)[\\:[0-9]{1,4}]?([/\\w+]*)[\\.\\w+]*[?\\w+=\\w+][&\\w+=\\w+]*)",
					"$1<a target=\"_blank\" href=\"$2$3$4\">$2$3$4</a>"); //wzw:处理连接文本		

		return content;
	}
	

	/**
	 * <p>所有 html 标签，标签中的名称与 “<” or “</” 符号直接不能有空格，而与后面“>”之间可以有空格。</p>
	 * @author Zeven on 2011-5-19
	 * @param src
	 * @return
	 */
	public static boolean isContainsHtmlCode(String src){
		if (src==null) {
			return false;
		}
		String srcLcase = src.toLowerCase(); 
		return (srcLcase.indexOf("<html")>-1 && srcLcase.indexOf("<html")<srcLcase.indexOf("</html"))
			|| (srcLcase.indexOf("<font ")>-1 && srcLcase.indexOf("<font ")<srcLcase.indexOf("</font"))
			|| (srcLcase.indexOf("<a")>-1 && srcLcase.indexOf("<a")<srcLcase.indexOf("</a"))
			|| (srcLcase.indexOf("<b")>-1 && srcLcase.indexOf("<b")<srcLcase.indexOf("</b"))
			|| (srcLcase.indexOf("<i")>-1 && srcLcase.indexOf("<i")<srcLcase.indexOf("</i"))
			|| (srcLcase.indexOf("<pre")>-1 && srcLcase.indexOf("<pre")<srcLcase.indexOf("</pre"))
			|| (srcLcase.indexOf("<center")>-1 && srcLcase.indexOf("<center")<srcLcase.indexOf("</center"));
	}

	public static boolean needAddAnchorHtmlCode(String src) {
		if (src==null) {
			return false;
		}
		String srcLcase = src.toLowerCase(); 
		return (srcLcase.indexOf("<html")<0 && srcLcase.indexOf("</html")<0)
			&& (srcLcase.indexOf("<a")<0 && srcLcase.indexOf("<a")<srcLcase.indexOf("</a"));
	}

	public static Date getNextBeginTime(String initTimeStr, String intervalType,
			String intervalNum) throws ParseException {
		return getNextBeginTime(initTimeStr, intervalType, Long.parseLong(intervalNum) );
	}
	
	public static Date getNextBeginTime(String initTimeStr, String intervalType,
			long intervalNum) throws ParseException {

		log.debug(initTimeStr+" "+intervalType+" "+intervalNum);

		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dt_initTime=sdf.parse(initTimeStr);
		if (intervalNum<1) {
			return dt_initTime;
		}
		
		Calendar cl_today = Calendar.getInstance();
		Calendar cl_initTime = Calendar.getInstance();
		cl_initTime.setTime(dt_initTime);
		//Calendar cd_today = Calendar.getInstance();
		long timeOffSet = cl_today.getTime().getTime()-cl_initTime.getTime().getTime();
		
		Date initTime=sdf.parse(initTimeStr);
		Date dt_today = Calendar.getInstance().getTime();
		long timeOffSet2 = dt_today.getTime()-initTime.getTime();
		
		if (timeOffSet>0) { // must need add
			if ("year".equals(intervalType)) {
				int yearOffset = cl_today.get(Calendar.YEAR)-cl_initTime.get(Calendar.YEAR);
				//System.out.println(yearOffset);
				yearOffset = yearOffset%(int)intervalNum;
				//System.out.println(yearOffset);
				if(yearOffset==0){   // 在同一年，但是有可能月份前后不同
					cl_initTime.set( Calendar.YEAR, cl_today.get(Calendar.YEAR) );
				}
				if(yearOffset>0 || cl_initTime.getTime().before(cl_today.getTime())){  // 有年级别差别或者月..级别时间差，补一个间隔期差值
					yearOffset = (int)intervalNum - yearOffset;
					//System.out.println(yearOffset);
					cl_initTime.set(Calendar.YEAR, cl_today.get(Calendar.YEAR) + yearOffset );
				}
				
			} else if ("month".equals(intervalType)) {
				int yearOffset = cl_today.get(Calendar.YEAR) - cl_initTime.get(Calendar.YEAR);
				int monthOffset = cl_today.get(Calendar.MONTH)-cl_initTime.get(Calendar.MONTH);
				//System.out.println(monthOffset);
				monthOffset = yearOffset*12 + monthOffset;
				//System.out.println(monthOffset);
				monthOffset = monthOffset%(int)intervalNum;
				//System.out.println(monthOffset);
				yearOffset = 0 ; // init if monthOffset=0 
				//System.out.println(monthOffset);
				if(monthOffset==0){  //跟今天没有月份级别的差别，但可能有天和时分秒的差别
					cl_initTime.set( Calendar.YEAR, cl_today.get(Calendar.YEAR) );
					cl_initTime.set( Calendar.MONTH, cl_today.get(Calendar.MONTH) );
				} 
				if( monthOffset>0 || cl_initTime.getTime().before(cl_today.getTime()) ){ // 有月份差别或者天时分秒差别。补上间隔期差值
					monthOffset = (int)intervalNum - monthOffset;					
					yearOffset = (monthOffset+cl_today.get(Calendar.MONTH))/12;  // convert 12 months to one year
					//System.out.println(yearOffset);  
					monthOffset = monthOffset - yearOffset*12;
					//System.out.println(monthOffset); 
					cl_initTime.set( Calendar.YEAR, cl_today.get(Calendar.YEAR) + yearOffset );
					cl_initTime.set(Calendar.MONTH, cl_today.get(Calendar.MONTH) + monthOffset );
				}
				
			} else {
				long intervalTimes = intervalNum * DirectorConstants.intervalUintsOffsetMap.get(intervalType);
				log.debug("intervalNum = "+intervalNum + " intervalTimes"+intervalTimes);
				timeOffSet = timeOffSet%intervalTimes; //wzw:get offset
				if(timeOffSet>0){  // if value=0,execute right now.
					timeOffSet = intervalTimes - timeOffSet;
				}
				dt_initTime = cl_initTime.getTime();
				dt_initTime.setTime(cl_today.getTime().getTime() + timeOffSet);
				cl_initTime.setTime(dt_initTime); //这样设置正确
				//cl_initTime.getTime().setTime(cl_today.getTime().getTime() + timeOffSet); //这样设置出错	
				//cl_today.add(Calendar.MILLISECOND, (int) timeOffSet); //这样设置也正确
			}
		}
		return cl_initTime.getTime();
	}

    /**                                                                               
     *                                                                                
     * @param datestr 日期字符串                                                      
     * @param day  相对天数，为正数表示之后，为负数表示之前                           
     * @return 指定日期字符串n天之前或者之后的日期                                    
     */                                                                               
    public static String getBeforeAfterDate(String datestr, int day) {         
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");                     
        java.sql.Date olddate = null;                                                 
        try {                                                                         
            df.setLenient(false);                                                     
            olddate = new java.sql.Date(df.parse(datestr).getTime());                 
        } catch (ParseException e) {                                                  
            throw new RuntimeException("日期转换错误");                               
        }                                                                             
        Calendar cal = new GregorianCalendar();                                       
        cal.setTime(olddate);                                                         
                                                                                      
        int Year = cal.get(Calendar.YEAR);                                            
        int Month = cal.get(Calendar.MONTH);                                          
        int Day = cal.get(Calendar.DAY_OF_MONTH);                                     
                                                                                      
        int NewDay = Day + day;                                                       
                                                                                      
        cal.set(Calendar.YEAR, Year);                                                 
        cal.set(Calendar.MONTH, Month);                                               
        cal.set(Calendar.DAY_OF_MONTH, NewDay);                                       
        
        return df.format( cal.getTime() );
//        return new java.sql.Date(cal.getTimeInMillis());                              
    }                                                                                 

	/**
	 * <p>java方法的说明...</p>
	 * @author Zeven on May 19, 2011
	 * @param args
	 */
	public static void main(String[] args) {
		Date dt = new Date();
		Calendar cl = Calendar.getInstance();
		cl.setTime(dt);
		System.out.println(dt.getYear());
		System.out.println(cl.get( Calendar.YEAR ));
		System.out.println(dt.getMonth());
		System.out.println(cl.get( Calendar.MONTH ));
		
		// TODO Auto-generated method stub
		String src = "全景网  http://www.p5w.net";
		System.out.println(addAnchorHtmlCode( src));
		System.out.println(addAnchorHtmlCode( " http://www.theServerSide.com"));
		System.out.println(addAnchorHtmlCode( "a http://172.16.168.112:7000/creatorepp/"));
	}

}
